<template>
  <v-main>
    <div id="container">
      <v-btn
        class="mt-8 mr-4 float-right locBtn"
        :color="gpsColor"
        text-color="white"
        rounded
      >
        <v-icon left> mdi-map-marker </v-icon>
        GPS
      </v-btn>
      <v-btn
        class="mt-8 mr-4 float-right locBtn"
        color="primary"
        text-color="white"
        rounded
        @click="clearHistory"
      >
        <v-icon left> mdi-delete-forever </v-icon>
        清除历史轨迹
      </v-btn>
      <v-btn
        class="mt-8 mr-4 float-right locBtn"
        color="primary"
        text-color="white"
        rounded
        @click="changeRefreshStatus"
      >
        <v-icon left> mdi-cached </v-icon>
        {{ refreshStatus }}
      </v-btn>
      <v-btn
        class="mt-8 mr-4 float-right locBtn"
        color="primary"
        text-color="white"
        rounded
        @click="refresh"
      >
        <v-icon left> mdi-cached </v-icon>
        手动刷新
      </v-btn>
    </div>
  </v-main>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  name: "Map",
  data() {
    return {
      refreshStatus: "自动刷新",
      gpsColor: "primary",
      refreshInterval: 0,
      gpsLocStatus: true,
      gpsPath: [],
      paintPath: [],
      polyline: {},
    };
  },
  methods: {
    loadMap: function () {
      let jeremy = this;
      AMapLoader.load({
        key: "3c618ebb54475fb63eb35b900519cd6f",
        version: "2.0",
      })
        .then((AMap) => {
          jeremy.map = new AMap.Map("container", {
            resizeEnable: true,
          });
          // 同时引入工具条插件，比例尺插件和鹰眼插件
          AMap.plugin(["AMap.ToolBar", "AMap.Scale"], function () {
            // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
            jeremy.map.addControl(
              new AMap.Scale({
                position: "RB",
              })
            );
          });
        })
        .catch((e) => {
          console.log(e);
        });
    },
    clearHistory: function () {
      this.gpsPath = [];
      this.paintPath = [];
      this.polyline = {};
      let clearGPSHistoryConfig = {
        url:
          "http://airtest.openluat.com:2900/clearGPSHistory/" +
          localStorage.deviceID,
        method: "get",
      };
      this.axios(clearGPSHistoryConfig).catch(function (error) {
        alert("清除历史记录出错");
        console.log(error);
      });
    },
    changeRefreshStatus: function () {
      let refreshStatus = this.refreshStatus;
      if (refreshStatus === "自动刷新") {
        this.refreshStatus = "刷新中";
        this.refreshInterval = setInterval(this.refresh, 5000);
      } else {
        this.refreshStatus = "自动刷新";
        clearInterval(this.refreshInterval);
      }
    },
    refresh: function () {
      this.gpsPath = [];
      this.paintPath = [];
      this.polyline = null;
      let jeremy = this;
      if (localStorage.deviceID == 0) {
        alert("请先设置DeviceID");
        return;
      }
      let getGPSAxiosConfig = {
        url:
          "http://airtest.openluat.com:2900/getGPSLocInfoList/" +
          localStorage.deviceID,
        method: "get",
      };
      this.axios(getGPSAxiosConfig)
        .then(function (res) {
          if (res) {
            let pathTmp = res.data;
            for (let i = 0; i < pathTmp.length; i++) {
              jeremy.gpsPath.push(JSON.parse(pathTmp[i]));
            }
            if (jeremy.gpsPath.length === 0) {
              console.log("return");
              return;
            }

            for (let i = 0; i < jeremy.gpsPath.length; i++) {
              AMap.convertFrom(
                [jeremy.gpsPath[i].lng, jeremy.gpsPath[i].lat],
                "gps",
                function (status, result) {
                  if (result.info === "ok") {
                    var lngAndlat = result.locations;
                    let gdLng = lngAndlat[0].lng;
                    let gdLat = lngAndlat[0].lat;
                    jeremy.paintPath[i] = [gdLng, gdLat];
                  }
                  for (let j = 0; j < jeremy.paintPath.length; j++) {
                    if (jeremy.paintPath[j] == null) {
                      return;
                    }
                  }

                  jeremy.polyline = new AMap.Polyline({
                    path: jeremy.paintPath,
                    isOutline: true,
                    outlineColor: "#ffeeff",
                    borderWeight: 3,
                    strokeColor: "#3366FF",
                    strokeOpacity: 1,
                    strokeWeight: 10,
                    strokeStyle: "solid",
                    strokeDasharray: [10, 5],
                    lineJoin: "round",
                    lineCap: "round",
                    zIndex: 50,
                    showDir: true,
                  });

                  jeremy.map.add(jeremy.polyline);
                  jeremy.map.setFitView();
                }
              );
            }
          } else {
            console.log("axios error");
          }
        })
        .catch(function (error) {
          alert("找不到DeviceID对应的轨迹");
          console.log(error);
        });

      //   AMap.convertFrom(
      //     [jeremy.gpsLocInfo.lng, jeremy.gpsLocInfo.lat],
      //     "gps",
      //     function (status, result) {
      //       if (result.info === "ok") {
      //         var lngAndlat = result.locations;
      //         let gdLng = lngAndlat[0].lng;
      //         let gdLat = lngAndlat[0].lat;
      //         let point = new AMap.LngLat(gdLng, gdLat);
      //         let unixTimestamp = new Date(jeremy.gpsLocInfo.timestamp * 1000);
      //         let commonTime = unixTimestamp.toLocaleString();
      //         jeremy.gpsMarker = new AMap.Marker({
      //           position: point,
      //           label: {
      //             content: `GPS\r\nLng:${gdLng}, Lat:${gdLat}, ${commonTime}`,
      //             direction: "top",
      //           },
      //           icon: new AMap.Icon({
      //             size: new AMap.Size(19, 26),
      //             image:
      //               "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png",
      //             imageSize: new AMap.Size(19, 26),
      //           }),
      //         });

      //         jeremy.map.add(jeremy.gpsMarker);
      //         jeremy.map.setFitView();
      //       }
      //     }
      //   );
    },
  },
  watch: {},
  mounted() {
    this.loadMap();
  },
};
</script>
<style scoped>
#container {
  width: 100%;
  height: 100%;
}

.locBtn {
  z-index: 1;
}
</style>
